<template>
    <div class="icontent">
        <div class="logincontent">
            <input type="text" id="message" value="Hello, World!"/>
            <button type="button" id="connect_websocket">连接 websocket</button>
            <button type="button" id="send_message">发送 message</button>
            <button type="button" id="close_websocket">关闭 websocket</button>
            <h1>Received Messages</h1>
            <div id="messagecontainer">

            </div>
        </div>
    </div>
</template>

<script>
    import { login, getInfo } from '@/api/login'
    import store from '@/store'
    import Vue from 'vue'
    import $ from 'jquery'

    $(function () {
        $('#connect_websocket').click(function () {
            if (window.s) {
                window.s.close()
            }
            /*创建socket连接*/
            var socket = new WebSocket("ws://127.0.0.1:8000/account/echo");
            socket.onopen = function () {
                console.log('WebSocket open');//成功连接上Websocket
            };
            socket.onmessage = function (e) {
                console.log('message: ' + e.data);//打印出服务端返回过来的数据
                $('#messagecontainer').prepend('<p>' + e.data + '</p>');
            };
            // Call onopen directly if socket is already open
            if (socket.readyState == WebSocket.OPEN) socket.onopen();
            window.s = socket;
        });
        $('#send_message').click(function () {
            //如果未连接到websocket
            if (!window.s) {
                alert("websocket未连接.");
            } else {
                window.s.send($('#message').val());//通过websocket发送数据
            }
        });
        $('#close_websocket').click(function () {
            if (window.s) {
                window.s.close();//关闭websocket
                console.log('websocket已关闭');
            }
        });

    });

    export default {
        name: "chat",
        data () {
            return {
                name:'aea'
            }
        },
        methods: {
            
        },
        created: function() {
        }
    }
</script>

<style scoped>
    .icontent{
        width: 90%;
        height: 100%;
        margin: 0 5% 0 5%;
        overflow: hidden;
    }
    .logincontent{
        width: 90%;
        height: 100%;
        margin: 50px 5% 0 5%;
        overflow: hidden;
        text-align: center;
    }
</style>